from qgis.core import QgsTextAnnotation, QgsPointXY
from qgis.gui import QgsMapCanvasAnnotationItem
from PyQt5.QtGui import QTextDocument
import os

from qgis.utils import iface

# === 1. 获取当前激活图层并其左上角坐标 ===
layer = iface.activeLayer()
if not layer:
    raise Exception("No active layer found!")

extent = layer.extent()
top_left = QgsPointXY(extent.xMinimum(), extent.yMaximum())

# === 2. 构建注记内容 ===
data_folder = "/Users/kai.han/code/qgis-sbeb-fdeb/data/network"
nc_stats_path = os.path.join(data_folder, 'gen_networkchars.csv')
        

# 检查文件是否存在
if not os.path.exists(nc_stats_path):
    print(f"NC stats file not found at {nc_stats_path}")


stats_info = ""
with open(nc_stats_path, 'r') as f:
    headers = next(f).strip().split(',')
    
    for line in f:
        parts = line.strip().split(',')
        stats_info += f"{parts[0]}: {parts[1]}\t"

# === 3. 创建注记对象并设置文本 ===
annotation = QgsTextAnnotation()
doc = QTextDocument()
doc.setPlainText(stats_info)
annotation.setDocument(doc)

# === 4. 设置注记在图层左上角位置 ===
annotation.setMapPosition(top_left)
annotation.setMarkerSymbol(None)      # 去掉红色锚点（重点）
annotation.setHasFixedMapPosition(True)  # 固定注记，不显示线

# === 5. 添加到地图画布上 ===
canvas_item = QgsMapCanvasAnnotationItem(annotation, iface.mapCanvas())

print(f"✅ 注记 {stats_info} 已成功添加到图层左上角！")
